package com.drinkian.business.good.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.drinkian.authentication.entity.po.User;
import com.drinkian.authentication.mapper.UserMapper;
import com.drinkian.business.good.entity.po.Good;
import com.drinkian.business.good.entity.po.GoodPicture;
import com.drinkian.business.good.entity.vo.VGoodAdd;
import com.drinkian.business.good.entity.vo.VGoodGet;
import com.drinkian.business.good.mapper.GoodMapper;
import com.drinkian.business.good.mapper.GoodPictureMapper;
import com.drinkian.business.good.service.IGoodService;
import com.drinkian.entity.RequestResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

@Service
public class GoodServiceImpl implements IGoodService {

    @Autowired
    private GoodMapper goodMapper;

    @Autowired
    private GoodPictureMapper goodPictureMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public RequestResult addGood(VGoodAdd vGoodAdd) {
        vGoodAdd.setOriginPrice(String.valueOf((int) (Double.valueOf(vGoodAdd.getOriginPrice()) * 100)));
        vGoodAdd.setSellPrice(String.valueOf((int) (Double.valueOf(vGoodAdd.getSellPrice()) * 100)));
        Good good = new Good();
        BeanUtils.copyProperties(vGoodAdd, good);
        int result = goodMapper.addGoodBasic(good);
        if (result == 1) {
            for (String imageUrl : vGoodAdd.getImageArr()) {
                goodMapper.addGoodImage(good.getId(), imageUrl);
            }
            return new RequestResult(HttpStatus.OK.value(), "添加成功！请等待审核通过！");
        } else {
            return new RequestResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), "添加商品信息出现了错误，请重试");
        }
    }

    @Override
    public RequestResult getGoodList(int current, int size) {
        IPage<VGoodGet> vGoodGetIPage = new Page<>(current, size);
        List<VGoodGet> goodList = goodMapper.getGoodList(vGoodGetIPage).getRecords();
        for (VGoodGet vGoodGet : goodList) {
            List<String> goodImageList = goodMapper.getGoodImageList(vGoodGet.getGoodId());
            vGoodGet.setGoodImage(goodImageList);
        }
        return new RequestResult(HttpStatus.OK.value(), goodList);
    }

    @Override
    public RequestResult searchGood(String name) {
        List<VGoodGet> vGoodGets = goodMapper.searchGood(name);
        for (VGoodGet vGoodGet : vGoodGets) {
            List<String> goodImageList = goodMapper.getGoodImageList(vGoodGet.getGoodId());
            vGoodGet.setGoodImage(goodImageList);
        }
        return new RequestResult(HttpStatus.OK.value(), vGoodGets);
    }

    @Override
    public RequestResult getGoodListByUploaderId(int id, int current, int size) {
        IPage<Good> iPage = new Page<>(current, size);
        QueryWrapper<Good> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uploader_id", id).orderByDesc("modify_time");
        IPage<Good> goodIPage = goodMapper.selectPage(iPage, queryWrapper);
        for (Good good : goodIPage.getRecords()) {
            QueryWrapper<GoodPicture> goodPictureQueryWrapper = new QueryWrapper<>();
            goodPictureQueryWrapper.eq("good_id", good.getId());
            List<GoodPicture> goodPictureList = goodPictureMapper.selectList(goodPictureQueryWrapper);
            good.setImage(goodPictureList);
        }
        return new RequestResult(HttpStatus.OK.value(), goodIPage);
    }


    @Override
    public RequestResult deleteGoodById(int id) {
        UpdateWrapper<Good> goodUpdateWrapper = new UpdateWrapper<>();
        goodUpdateWrapper.eq("id", id).set("deleted", 1);
        int goodRows = goodMapper.update(null, goodUpdateWrapper);
        if (goodRows == 1) {
            UpdateWrapper<GoodPicture> goodPictureUpdateWrapper = new UpdateWrapper<>();
            goodPictureUpdateWrapper.eq("good_id", id).set("deleted", 1);
            int pictureRows = goodPictureMapper.update(null, goodPictureUpdateWrapper);
            if (pictureRows > 0) {
                return new RequestResult(HttpStatus.OK.value(), "删除成功！");
            } else {
                return new RequestResult(HttpStatus.OK.value(), "商品删除成功！图片还未删除。");
            }
        } else {
            return new RequestResult(HttpStatus.OK.value(), "商品删除失败！");
        }
    }

    @Override
    public RequestResult updateGood(Good good) {
        good.setOriginPrice(String.valueOf((int) (Double.valueOf(good.getOriginPrice()) * 100)));
        good.setSellPrice(String.valueOf((int) (Double.valueOf(good.getSellPrice()) * 100)));
        good.setModifyTime(null);
        int result = goodMapper.updateById(good);
        if (result == 1) {
            return new RequestResult(HttpStatus.OK.value(), "更新成功！");
        } else {
            return new RequestResult(HttpStatus.SERVICE_UNAVAILABLE.value(), "服务器错误！");
        }
    }

    @Override
    public RequestResult getUncheckGoodList(Integer current, Integer size) {
        IPage<Good> iPage = new Page<>(current, size);
        QueryWrapper<Good> goodQueryWrapper = new QueryWrapper<>();
        goodQueryWrapper.eq("status", 0);
        IPage<Good> goodIPage = goodMapper.selectPage(iPage, goodQueryWrapper);
        Iterator<Good> iterator = goodIPage.getRecords().iterator();
        while (iterator.hasNext()) {
            Good next = iterator.next();
            // 添加上传人信息
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>();
            userQueryWrapper.eq("status", 2);
            userQueryWrapper.eq("id", next.getUploaderId());
            User uploader = userMapper.selectOne(userQueryWrapper);

            // 用户不存在或者违规
            if (Objects.isNull(uploader)) {
                iterator.remove();
            } else {
                next.setUploader(uploader);
            }

            // 添加商品图片信息
            QueryWrapper<GoodPicture> goodPictureQueryWrapper = new QueryWrapper<>();
            goodPictureQueryWrapper.eq("status", 1);
            goodPictureQueryWrapper.eq("deleted", 0);
            goodPictureQueryWrapper.eq("good_id", next.getId());
            List<GoodPicture> pictures = goodPictureMapper.selectList(goodPictureQueryWrapper);
            next.setImage(pictures);
        }
        return new RequestResult(HttpStatus.OK.value(), goodIPage);
    }

    @Override
    public RequestResult examUncheckGood(Integer goodId, Integer code) {
        QueryWrapper<Good> goodQueryWrapper = new QueryWrapper<>();
        goodQueryWrapper.eq("id", goodId);
        goodQueryWrapper.eq("status", 0);
        Good good = goodMapper.selectOne(goodQueryWrapper);
        // 审核失败
        if (code == 0) {
            good.setStatus(2);
            int update = goodMapper.updateById(good);
            if (update == 1) {
                // 获得商品发布人信息
                QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                userQueryWrapper.eq("id", good.getUploaderId());
                User uploader = userMapper.selectOne(userQueryWrapper);

                // 发送通知邮件
                SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
                simpleMailMessage.setSubject("HBUShop发布审核结果");
                simpleMailMessage.setText("您在 " + good.getCreateTime().format(dateTimeFormatter) + " 发布的  " + good.getName() + " 未通过审核，请修改后重新提交！");
                simpleMailMessage.setFrom("2294422096@qq.com");
                simpleMailMessage.setTo(uploader.getEmail());
                javaMailSender.send(simpleMailMessage);
                return new RequestResult(HttpStatus.OK.value(), "驳回成功！");
            } else {
                return new RequestResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), "服务器错误！");
            }
        } else if (code == 1) {         // 审核通过
            good.setStatus(1);
            int update = goodMapper.updateById(good);
            if (update == 1) {
                // 获得商品发布人信息
                QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                userQueryWrapper.eq("id", good.getUploaderId());
                User uploader = userMapper.selectOne(userQueryWrapper);

                // 发送通知邮件
                SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
                simpleMailMessage.setSubject("HBUShop发布审核结果");
                simpleMailMessage.setText("您在 " + good.getCreateTime().format(dateTimeFormatter) + " 发布的  " + good.getName() + " 已经通过了审核！");
                simpleMailMessage.setFrom("2294422096@qq.com");
                simpleMailMessage.setTo(uploader.getEmail());
                javaMailSender.send(simpleMailMessage);
                return new RequestResult(HttpStatus.OK.value(), "审核通过！");
            } else {
                return new RequestResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), "服务器错误！");
            }
        } else {
            return new RequestResult(HttpStatus.BAD_REQUEST.value(), "提交的参数有误！");
        }
    }
}
